package com.banyou.banyou.main.search;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;

import com.alibaba.fastjson.JSON;
import com.banyou.banyou.R;
import com.banyou.banyou.adapter.SearchAdapter;
import com.banyou.banyou.base.BaseFragment;
import com.banyou.banyou.bean.main.search.SearchInfo;
import com.banyou.banyou.bean.main.search.SearchListBean;
import com.banyou.banyou.main.MainActivity;
import com.banyou.banyou.main.info.InfoActivity;
import com.banyou.banyou.util.EditDialogFactory;
import com.banyou.banyou.util.ShowAddressPicker;
import com.banyou.banyou.util.ShowToast;
import com.banyou.banyou.util.SpacesItemDecoration;
import com.banyou.banyou.webutils.ProgressSubscriber;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import cn.qqtheme.framework.picker.DoublePicker;
import cn.qqtheme.framework.picker.NumberPicker;
import cn.qqtheme.framework.picker.OptionPicker;

import static android.support.v7.widget.StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS;

/**
 * ----------Dragon be here!----------/
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃代码无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * 类描述：
 * 创建人：Random
 * 修改时间：
 * 修改备注：
 */

public class SearchFragment extends
        BaseFragment<SearchPresenter> implements SearchContract.View {


    @BindView(R.id.search_btn_content)
    HorizontalScrollView mSearchBtnContent;
    @BindView(R.id.main_recycler)
    RecyclerView mMainRecycler;
    @BindView(R.id.area_btn)
    Button mAreaBtn;
    @BindView(R.id.sex_btn)
    Button mSexBtn;
    @BindView(R.id.age_btn)
    Button mAgeBtn;
    @BindView(R.id.star_btn)
    Button mStarBtn;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.name_btn)
    Button mNameBtn;
    @BindView(R.id.journey_btn)
    Button mJourneyBtn;

    private List<SearchListBean> mSearchList = new ArrayList<>();
    private SearchAdapter mAdapter;
    private Map<String, String> mOriginMap;
    private String mStartAge = "-1", mEndAge = "-1";
    private SearchInfo mSearchInfo = new SearchInfo();
    private int mStart = 0, mLimit = 10, mTotal;


    @Override
    protected void init() {
        mPresenter.initPresenter(this, new SearchModel());
        initRecyclerView();
        mOriginMap = new HashMap<>();
        String userType = getSharedPreference().getString("userType", "1");
        if (userType.equals("1")) {
            mOriginMap.put("userType", "2");
        } else {
            mOriginMap.put("userType", "1");
        }
        mOriginMap.put("start", "0");
        mOriginMap.put("limit", "5");
        mPresenter.getData(mOriginMap);
        mRefreshLayout.setOnRefreshListener(mOnRefreshListener);
        initSearchInfo();//初始化Search内容
        mSearchBtnContent.setHorizontalScrollBarEnabled(false);//去导航条
        mMainRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
                //屏幕中最后一个可见子项的position
                int[] lastVisibleItemPosition = layoutManager.findLastVisibleItemPositions(null);
                //当前屏幕所看到的子项个数
                int visibleItemCount = layoutManager.getChildCount();
                //当前RecyclerView的所有子项个数
                int totalItemCount = layoutManager.getItemCount();
                if (visibleItemCount > 0 && (lastVisibleItemPosition[1] == totalItemCount - 1 || lastVisibleItemPosition[0] == totalItemCount - 1) && newState == RecyclerView.SCROLL_STATE_IDLE && mLimit * (mStart + 1) <= mTotal) {
                    mOriginMap.put("start", "" + mStart++);
                    mPresenter.getData(mOriginMap);
                }
            }
        });
    }

    void initBtn() {
        mAreaBtn.setText("地区");
        mAreaBtn.setTextColor(getResources().getColor(R.color.text_deap_gray));
        mSexBtn.setText("性别");
        mSexBtn.setTextColor(getResources().getColor(R.color.text_deap_gray));
        mAgeBtn.setText("年龄");
        mAgeBtn.setTextColor(getResources().getColor(R.color.text_deap_gray));
        mStarBtn.setText("星级");
        mStarBtn.setTextColor(getResources().getColor(R.color.text_deap_gray));
        mNameBtn.setText("姓名");
        mNameBtn.setTextColor(getResources().getColor(R.color.text_deap_gray));

        initSearchInfo();
    }

    /**
     * 初始化Search内容
     */
    private void initSearchInfo() {
        mSearchInfo=new SearchInfo();
        mSearchInfo.setAttributes(new SearchInfo.AttributesBean());
        mSearchInfo.getAttributes().setBeginAge(-1);
        mSearchInfo.getAttributes().setEndAge(-1);
//        mSearchInfo.setLevel(1);
//        mSearchInfo.setRegionId("1101");
//        mSearchInfo.setSex("M");
//        mSearchInfo.setUserName("");
//        mSearchInfo.setUserType("2");

    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        manager.setGapStrategy(GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
        mMainRecycler.setLayoutManager(manager);
        mAdapter = new SearchAdapter(getActivity(), mSearchList);
        SpacesItemDecoration decoration = new SpacesItemDecoration(10);
        mMainRecycler.addItemDecoration(decoration);
        mMainRecycler.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new SearchAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                Intent intent = new Intent(getActivity(), InfoActivity.class);
                intent.putExtra("userId", mSearchList.get(position).getUSER_ID());
                startActivity(intent);
                //TODO 按下标点击进入
            }
        });
    }

    SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            mSearchList.clear();
            mPresenter.getData(mOriginMap);
            initBtn();
        }
    };

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_search;
    }

    @Override
    protected SearchPresenter initPresenter() {
        return new SearchPresenter();
    }


    @OnClick({R.id.area_btn, R.id.sex_btn, R.id.age_btn, R.id.star_btn, R.id.name_btn, R.id.journey_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.area_btn:
                addressPicker();//地址选择器
                break;
            case R.id.sex_btn:
                sexPicker();//性别选择器
                break;
            case R.id.age_btn:
                agePicker();//年龄选择器
                break;
            case R.id.star_btn:
                startPicker();//星星选择器
                break;
            case R.id.name_btn:
                createNameDialog();//弹出姓名选择框
                break;
            case R.id.journey_btn:
                createJourneyDialog();//弹出景点查询选择框
                break;
        }
    }

    /**
     * 弹出景点查询选择框
     */
    private void createJourneyDialog() {
        EditDialogFactory.makeOneEditDialog(getActivity(), "请输入景点", "景点", new EditDialogFactory.OnSureClickListener() {
            @Override
            public void onSureClick(EditText edit) {
                mJourneyBtn.setText(edit.getText().toString());
                mJourneyBtn.setTextColor(getResources().getColor(R.color.orange_ff9933));
                mSearchInfo.setRemarks(edit.getText().toString());
                mPresenter.search(JSON.toJSONString(mSearchInfo), mLimit + "", mStart + "");
            }
        });
    }

    /**
     * 弹出姓名输入Dialog
     */
    private void createNameDialog() {
        EditDialogFactory.makeOneEditDialog(getActivity(), "请输入姓名", "姓名", new EditDialogFactory.OnSureClickListener() {
            @Override
            public void onSureClick(EditText edit) {
                mNameBtn.setText(edit.getText().toString());
                mNameBtn.setTextColor(getResources().getColor(R.color.orange_ff9933));
                mSearchInfo.setUserName(edit.getText().toString());
                mPresenter.search(JSON.toJSONString(mSearchInfo), mLimit + "", mStart + "");
            }
        });
    }

    /**
     * 星级选择器
     */
    private void startPicker() {
        NumberPicker picker = new NumberPicker(getActivity());
        picker.setRange(1, 5, 1);
        picker.setLabel("星");
        picker.setSelectedItem(1);
        picker.setOnNumberPickListener(new NumberPicker.OnNumberPickListener() {
            @Override
            public void onNumberPicked(int index, Number item) {
                mStarBtn.setText(item.intValue() + "星");
                mStarBtn.setTextColor(getResources().getColor(R.color.orange_ff9933));
                mSearchInfo.setLevel(item.intValue());
                mPresenter.search(JSON.toJSONString(mSearchInfo), mLimit + "", mStart + "");
            }
        });
        picker.show();
    }

    /**
     * 年龄选择器
     */
    private void agePicker() {
        final List<String> list = new ArrayList<>();
        for (int i = 10; i < 99; i++) {
            list.add(i + "");
        }
        final DoublePicker picker = new DoublePicker(getActivity(), list, list);
        picker.setDividerVisible(true);
        picker.setCycleDisable(false);
        picker.setSelectedIndex(1, 2);
        picker.setOnPickListener(new DoublePicker.OnPickListener() {
            @Override
            public void onPicked(int selectedFirstIndex, int selectedSecondIndex) {
                if (selectedFirstIndex < selectedSecondIndex) {
                    mAgeBtn.setText(list.get(selectedFirstIndex) + "-" + list.get(selectedSecondIndex) + "岁");
                    mAgeBtn.setTextColor(getResources().getColor(R.color.orange_ff9933));
                    mStartAge = list.get(selectedFirstIndex);
                    mEndAge = list.get(selectedSecondIndex);
                    mSearchInfo.getAttributes().setBeginAge(Integer.parseInt(mStartAge));
                    mSearchInfo.getAttributes().setEndAge(Integer.parseInt(mEndAge));
                    mPresenter.search(JSON.toJSONString(mSearchInfo), mLimit + "", mStart + "");
                } else {
                    ShowToast.showToast("起始年龄必须小于结束年龄");
                }


            }
        });
        picker.show();
    }

    /**
     * 选择性别
     */
    private void sexPicker() {
        OptionPicker picker = new OptionPicker(getActivity(), new String[]{"男", "女"});
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                mSexBtn.setText(item);
                mSexBtn.setTextColor(getResources().getColor(R.color.orange_ff9933));

                if (item.equals("男")) {
                    mSearchInfo.setSex("M");
                } else {
                    mSearchInfo.setSex("F");
                }
                mPresenter.search(JSON.toJSONString(mSearchInfo), mLimit + "", mStart + "");
            }
        });
        picker.show();
    }

    /**
     * 选择地址
     */
    private void addressPicker() {
        MainActivity activity = (MainActivity) getActivity();
        ShowAddressPicker.show(activity, new ShowAddressPicker.OnCityPickedCallBack() {
            @Override
            public void onAddressPicked(Province province, City city, County county) {
                mAreaBtn.setText(city.getName());
                mAreaBtn.setTextColor(getResources().getColor(R.color.orange_ff9933));
                mSearchInfo.setRegionId((String) city.getId());
                mPresenter.search(JSON.toJSONString(mSearchInfo), mLimit + "", mStart + "");
            }
        });
    }

    /**
     * 获取数据成功
     *
     * @param beans
     */
    @Override
    public void getDataSuccess(List<SearchListBean> beans) {
        mRefreshLayout.setRefreshing(false);
        mTotal = beans.get(0).getTotal();
        beans.remove(0);
        mSearchList.addAll(beans);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 获取数据失败
     *
     * @param e
     */
    @Override
    public void getDataFail(Throwable e) {
        if (e instanceof ProgressSubscriber.ReturnCodeErrorException) {
            ShowToast.showToast(((ProgressSubscriber.ReturnCodeErrorException) e).getMsg());
        } else {
            ShowToast.showToast("获取列表数据失败");
        }
        mRefreshLayout.setRefreshing(false);
    }
}
